import json
from base64 import b64encode
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.ocr.v20181119 import ocr_client, models
from Chat import ChatCompletions


class OcrTableAccurate:
    def __init__(self, secret_id, secret_key):
        self.secret_id = secret_id
        self.secret_key = secret_key

    def recognize_table_accurate(self, image_path):
        # 读取图片文件
        with open(image_path, "rb") as img_file:
            img_data = img_file.read()

        # 将图片转换为Base64编码
        image_base64 = b64encode(img_data).decode()

        # 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey
        cred = credential.Credential(self.secret_id, self.secret_key)

        # 实例化一个http选项，可选的，没有特殊需求可以跳过
        httpProfile = HttpProfile()
        httpProfile.endpoint = "ocr.tencentcloudapi.com"

        # 实例化一个client选项，可选的，没有特殊需求可以跳过
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        # 实例化要请求产品的client对象,clientProfile是可选的
        client = ocr_client.OcrClient(cred, "ap-guangzhou", clientProfile)

        # 实例化一个请求对象,每个接口都会对应一个request对象
        req = models.RecognizeTableAccurateOCRRequest()
        params = {
            "ImageBase64": image_base64
        }
        req.from_json_string(json.dumps(params))

        # 返回的resp是一个RecognizeTableAccurateOCRResponse的实例，与请求对象对应
        resp = client.RecognizeTableAccurateOCR(req)
        # 输出json格式的字符串回包
        return json.loads(resp.to_json_string())



if __name__ == "__main__":
    ocr = OcrTableAccurate("AKIDRmvrbAWfbP2UmrjNo6CHOSVREsbHqHWo", "IVZaQ3iGsMySjmcOwLYbUBeuxmOmwtd9")
    result = ocr.recognize_table_accurate(r"C:\Users\28128\Desktop\照片\微信图片_20250111120136.jpg ")
    print(result)






